#####################################################
### PAPER: THE ITALIAN POLITICAL CLASS
### FILE NAME: "7 - CFA Akkerman scale.R"
### AUTHOR: Isernia, Martini, Olmastroni, Verzichelli
#####################################################

# LOAD /INSTALL PACKAGES
pacman::p_load(tidyverse,  magrittr,  haven,  labelled,  descr,  lavaan,
  kutils,  stargazer,  car,  ltm,  semPlot,  margins,  prediction, semTable,  patchwork)

# SET WORKING DIRECTORY
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))

#DATA
akkerman <- read_dta("surveydata_01.dta") 

akkerman$P10_A[akkerman$P10_A==98] <- NA
akkerman$P10_B[akkerman$P10_B==98] <- NA
akkerman$P10_C[akkerman$P10_C==98] <- NA
akkerman$P10_D[akkerman$P10_D==98] <- NA
akkerman$P10_E[akkerman$P10_E==98] <- NA
akkerman$P10_F[akkerman$P10_F==98] <- NA

akkerman$P10_A[akkerman$P10_A==99] <- NA
akkerman$P10_B[akkerman$P10_B==99] <- NA
akkerman$P10_C[akkerman$P10_C==99] <- NA
akkerman$P10_D[akkerman$P10_D==99] <- NA
akkerman$P10_E[akkerman$P10_E==99] <- NA
akkerman$P10_F[akkerman$P10_F==99] <- NA

## AKKERMAN et al. ------------------------
akkerman %>% dplyr::select(
  P10_A, 
  P10_B, 
  P10_C, 
  P10_D, 
  P10_E,
  P10_F,
  id) -> AKK_CFA 

# CRONBAHC'S ALPHA
AKK_CFA[, 1:6] %>% cronbach.alpha(na.rm = T, standardized = T)

# MODEL
cfa.AKK_CFA <- "pop_AKK_CFA =~ P10_A + P10_B + P10_C + P10_D + P10_E + P10_F"

# FIT MODEL
fit_cfa.AKK_CFA <- cfa(cfa.AKK_CFA, data = as.matrix(AKK_CFA[, 1:6]), missing = "ml.x",
                        std.lv = F)
# RESULTS
summary(fit_cfa.AKK_CFA, fit.measures = T, standardized=TRUE)

# CHECK DIRECTION
cbind(AKK_CFA[, 1:6], as.vector(lavPredict(fit_cfa.AKK_CFA)))

# EXPORT SCORES
data.frame(AKK_CFA, as.vector(lavPredict(fit_cfa.AKK_CFA))) -> AKK_CFA
names(AKK_CFA)[ncol(AKK_CFA)] <- "AKK_CFA"

full_join(akkerman, 
          as_tibble(AKK_CFA[, c(ncol(AKK_CFA)-1, ncol(AKK_CFA))]), 
          by = "id") -> akkerman

# SUMMARY TABLE
semTable(fit_cfa.AKK_CFA, longtable = T,
         varLabels = c(
           "P10_A" = "Item 1",
           "P10_B" = "Item 2",
           "P10_C" = "Item 3",
           "P10_D" = "Item 4",
           "P10_E" = "Item 5",
           "P10_F" = "Item 6"
         ))

modEvA::range01(akkerman$AKK_CFA) -> akkerman$AKK_CFA

write_dta(akkerman, "surveydata_01_CFA.dta")
